<template>
  <!--故障处理配置 弹窗 -->
  <a-modal
    v-model:open="visible"
    class="addRule"
    destroyOnClose
    :width="modelWidth"
    @cancel="cancel"
    @ok="submit"
    :maskClosable="false"
    centered
  >
    <template v-slot:title>
      <div class="mainTitle">
        {{ props.isEdit ? "编辑故障记录" : "新增故障记录" }}
      </div>
    </template>
    <a-row :gutter="24" style="justify-content: center">
      <a-form
        :model="form"
        :rules="rules"
        layout="inline"
        ref="formRef"
        :labelCol="{
          style: {
            width: '140px',
          },
        }"
        :labelAlign="'right'"
      >
        <a-col :span="8">
          <a-form-item label="电站名称：" name="stationId">
            <a-select
              v-model:value="form.stationId"
              class="formSelect"
              placeholder="请选择"
              show-search
              optionFilterProp="label"
              allow-clear
            >
              <a-select-option
                v-for="item in stationNameOptions"
                :key="item.stationId"
                :value="item.stationId"
                :label="item.stationName"
              >
                {{ item.stationName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="电池柜容量(kWh)：" name="linkCap">
            <a-input
              v-model:value="form.linkCap"
              class="formInput"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障电池柜个数：" name="faultLinkNum">
            <a-input-number
              class="formInput"
              v-model:value="form.faultLinkNum"
              :controls="true"
              :min="0"
              step="1"
              @blur="handleBlur"
              placeholder="请输入"
            >
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障类别：" name="faultType">
            <a-select
              v-model:value="form.faultType"
              class="formSelect"
              placeholder="请选择"
              show-search
              optionFilterProp="label"
              allow-clear
            >
              <a-select-option
                v-for="item in faultTypeList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障细分：" name="faultSegment">
            <a-select
              v-model:value="form.faultSegment"
              class="formSelect"
              placeholder="请选择"
              show-search
              optionFilterProp="label"
              allow-clear
            >
              <a-select-option
                v-for="item in faultSegmentList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障归属：" name="faultBelong">
            <a-select
              v-model:value="form.faultBelong"
              class="formSelect"
              placeholder="请选择"
              show-search
              optionFilterProp="label"
              allow-clear
            >
              <a-select-option
                v-for="item in faultBelongList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障开始时间：" name="faultStartDate">
            <a-date-picker
              v-model:value="form.faultStartDate"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              show-time
              class="formSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障结束时间：" name="faultEndDate">
            <a-date-picker
              v-model:value="form.faultEndDate"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              show-time
              class="formSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="计划解决时间：" name="planResolveDate">
            <a-date-picker
              v-model:value="form.planResolveDate"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              show-time
              class="formSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="实际解决时间：" name="actualResolveDate">
            <a-date-picker
              v-model:value="form.actualResolveDate"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              show-time
              class="formSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否为计划停机：" name="planShutdown">
            <a-select
              v-model:value="form.planShutdown"
              class="formSelect"
              placeholder="请选择"
              disabled
            >
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="0">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否导致项目停运：" name="causeProjectShutdown">
            <a-select
              v-model:value="form.causeProjectShutdown"
              class="formSelect"
              placeholder="请选择"
            >
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="0">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障对接人：" name="faultContactPerson">
            <a-input
              v-model:value="form.faultContactPerson"
              class="formInput"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="影响第一次充放次数：" name="affectFirstNum">
            <a-input-number
              class="formInput"
              v-model:value="form.affectFirstNum"
              :controls="true"
              :min="0"
              step="1"
              @blur="handleBlur"
              placeholder="请输入"
            >
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="影响第二次充放次数：" name="affectSecondNum">
            <a-input-number
              class="formInput"
              v-model:value="form.affectSecondNum"
              :controls="true"
              :min="0"
              step="1"
              @blur="handleBlur"
              placeholder="请输入"
            >
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="故障现象描述：" name="faultDesc">
            <a-textarea
              v-model:value="form.faultDesc"
              placeholder="请输入"
              :auto-size="{ minRows: 3 }"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item name="faultDealDesc">
            <template #label> 处理方法描述 </template>
            <a-textarea
              v-model:value="form.faultDealDesc"
              placeholder="请输入"
              :auto-size="{ minRows: 3 }"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="总结建议描述：" name="summaryDesc">
            <a-textarea
              v-model:value="form.summaryDesc"
              placeholder="请输入"
              :auto-size="{ minRows: 3 }"
            />
          </a-form-item>
        </a-col>
      </a-form>
    </a-row>
  </a-modal>
</template>
<script setup>

import { FAULT_REGISTRATION_TYPE, FAULT_INFORMATION_TAB_ENUM } from "@/constants/faultRegistration.js"
const $api = inject("$api")
const modelWidth = computed(() => (window.innerWidth > 1805 ? "65%" : "85%"))
const props = defineProps({
  addFaultVisible: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: () => ({}),
  },
  stationList: {
    type: Array,
    default: () => [],
  },
  planShutdown: {
    type: Number,
  },
})
const loading = ref(false)
const visible = ref(props.addFaultVisible)
watch(
  () => props.addFaultVisible,
  (val) => {
    visible.value = val
    if (val) {
      getAllData()
      if (props.isEdit) {
        form.value = props.rowData
      } else {
        formRef.value?.resetFields()
      }
      form.value.planShutdown = props.planShutdown
    }
  }
)
const stationNameOptions = ref([])
watch(
  () => props.stationList,
  (val) => {
    stationNameOptions.value = val
  },
  {
    immediate: true,
  }
)
const form = ref({
  stationId: null,
  linkCap: null,
  faultLinkNum: null,
  faultType: null,
  faultSegment: null,
  faultBelong: null,
  faultStartDate: null,
  faultEndDate: null,
  planResolveDate: null,
  actualResolveDate: null,
  planShutdown: null,
  causeProjectShutdown: null,
  faultContactPerson: null,
  affectFirstNum: null,
  affectSecondNum: null,
  faultDesc: null,
  faultDealDesc: null,
  summaryDesc: null,
})

// 添加表单校验规则
const rules = {
  stationId: [{ required: true, message: "请选择电站名称", trigger: "change" }],
  linkCap: [{ required: true, message: "请输入电池柜容量", trigger: "blur" }],
  faultLinkNum: [
    { required: true, message: "请输入故障电池柜个数", trigger: "blur" },
  ],
  faultType: [{ required: true, message: "请选择故障类别", trigger: "change" }],
  faultSegment: [
    { required: true, message: "请选择故障细分", trigger: "change" },
  ],
  faultBelong: [
    { required: true, message: "请选择故障归属", trigger: "change" },
  ],
  faultStartDate: [
    { required: true, message: "请选择故障开始时间", trigger: "change" },
    {
      validator: (_, value) => {
        if (form.value.faultEndDate && value) {
          const startTime = new Date(value).getTime()
          const endTime = new Date(form.value.faultEndDate).getTime()
          if (startTime >= endTime) {
            return Promise.reject("开始时间必须小于结束时间")
          }
        }
        return Promise.resolve()
      },
      trigger: "change",
    },
  ],
  faultEndDate: [
    {
      validator: (_, value) => {
        if (form.value.faultStartDate && value) {
          const startTime = new Date(form.value.faultStartDate).getTime()
          const endTime = new Date(value).getTime()

          if (startTime >= endTime) {
            return Promise.reject("开始时间必须小于结束时间")
          }
        }
        return Promise.resolve()
      },
      trigger: "change",
    },
  ],
  planShutdown: [
    { required: true, message: "请选择是否计划停机", trigger: "change" },
  ],
  causeProjectShutdown: [
    { required: true, message: "请选择是否导致项目停运", trigger: "change" },
  ],
  faultContactPerson: [
    { required: true, message: "请输入故障对接人", trigger: "blur" },
  ],
  faultDesc: [
    { required: true, message: "请输入故障现象描述", trigger: "blur" },
  ],
}

const handleBlur = (val) => {
  if (val.target.value && !Number.isInteger(Number(val.target.value))) {
    message.error("请输入整数")
    return
  }
}
//获取故障类别/故障细分/故障归属的数据
const allData = ref([]) // 用于存储整理后的数据
const getAllData = async () => {
  // 初始化allData，根据FAULT_REGISTRATION_TYPE创建基础结构
  allData.value = FAULT_REGISTRATION_TYPE.filter((e) => e.type <= 3).map(
    (item) => {
      return {
        [item.type]: [],
      }
    }
  )

  // 创建所有请求的Promise数组

  const promises = allData.value.map((item, index) =>
    getList(Number(Object.keys(item)), index)
  )
}
const faultTypeList = ref([])
const faultSegmentList = ref([])
const faultBelongList = ref([])
const getList = async (type, index) => {
  let params = {
    configType: props.planShutdown ? FAULT_INFORMATION_TAB_ENUM.PlannedOutage : FAULT_INFORMATION_TAB_ENUM.Handling,
    type: type,
  }
  let res = await $api.faultConfigList(params)
  if (res && res.data) {
    if (type == 1) {
      faultTypeList.value = res.data
    } else if (type == 3) {
      faultSegmentList.value = res.data
    } else if (type == 2) {
      faultBelongList.value = res.data
    }
    //allData.value[index] = res.data
  }
}
const emits = defineEmits(["update:addFaultVisible", "refresh"])
const formRef = ref(null)
const cancel = () => {
  emits("update:addFaultVisible", false)
  form.value = {
    stationId: null,
    linkCap: null,
    faultLinkNum: null,
    faultType: null,
    faultSegment: null,
    faultBelong: null,
    faultStartDate: null,
    faultEndDate: null,
    planResolveDate: null,
    actualResolveDate: null,
    planShutdown: props.planShutdown,
    causeProjectShutdown: null,
    faultContactPerson: null,
    affectFirstNum: null,
    affectSecondNum: null,
    faultDesc: null,
    faultDealDesc: null,
    summaryDesc: null,
  }
  formRef.value?.resetFields()
}
const submit = async () => {
  try {
    await formRef.value.validate()
    form.value.planShutdown = props.planShutdown
    let res = await $api.faultDealSaveOrUpdate(form.value)
    if (res && res.code === 0) {
      emits("refresh")
      message.success("操作成功")
      cancel()
    }
  } catch (error) {
    console.error("表单校验失败", error)
  }
}
</script>
<style lang="less" scoped>
.mainTitle {
  margin-bottom: 30px;
}
.formInput,
.formSelect {
  width: 100%;
}
:deep(.ant-form-item) {
  margin-bottom: 20px;
}
</style>
